package com.fll.fangyishare.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.aliyun.oss.ServiceException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fll.fangyicommon.entity.ResultOk;
import com.fll.fangyicommon.entity.share.Oss;
import com.fll.fangyicommon.entity.share.Share;
import com.fll.fangyicommon.entity.user.User;
import com.fll.fangyicommon.utils.OssUtil;
import com.fll.fangyicommon.utils.TimeUtil;
import com.fll.fangyishare.service.OssService;
import com.fll.fangyishare.service.ShareService;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author fll
 * create 2023/3/20
 */
@RestController
@Slf4j
@RequestMapping("/share")
public class ShareController {

    @Autowired
    private OssService ossService;

    @Autowired
    private ShareService shareService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //上传说说图
    @PostMapping("/uploadImg")
    public ResultOk uploadImg(@RequestParam("file") MultipartFile file, @RequestHeader String userInfo) {

        ResultOk<String> ok = new ResultOk<>();
        User user = null;
        try {
            //将请求头中的user信息系列化成user对象
            user = new ObjectMapper().readValue(userInfo, User.class);

            String fileName = OssUtil.genName(file.getOriginalFilename(), user.getUserId(), "share");
            String fileUrl = OssUtil.upload(file.getBytes(), fileName);
            ok.setCode(200);
            ok.setMsg("上传成功");
            ok.setData(fileUrl);
            return ok;
        } catch (Exception e) {
            e.printStackTrace();
            ok.setCode(503);
            ok.setMsg("后端异常！");
            return ok;
        }
    }

    //上传说说图
    @PostMapping("/sendShare")
    @Transactional
    public ResultOk sendShare(@RequestBody Map<String, Object> params, @RequestHeader String userInfo) throws JsonProcessingException {
        ResultOk ok = new ResultOk<>();
        User user = null;

        user = new ObjectMapper().readValue(userInfo, User.class);
        String shareContent = (String)params.get("shareContent");
        Share share = new Share();
        share.setUserId(user.getUserId());
        share.setShareContent(shareContent);
        share.setCreateTime(TimeUtil.getString(new Date()));
        Integer num = shareService.addShare(share);
        if (num != -1){
            ArrayList<String> ossUtlList = (ArrayList<String>) params.get("oss");

            if (ossUtlList != null && ossUtlList.size() != 0){
                ArrayList<Oss> ossArrayList = new ArrayList<>();

                for (String url : ossUtlList){
                    Oss oss = new Oss();
                    oss.setShareId(share.getShareId());
                    oss.setUrl(url);
                    ossArrayList.add(oss);
                }
                Integer num2 = ossService.addShareOss(ossArrayList);
                if (num2 == null){
                    throw new ServiceException("发布说说失败，开始事务处理");
                }
            }
            ok.setCode(200);
            ok.setMsg("发布成功");
            return ok;
        }
        ok.setCode(500);
        ok.setMsg("发布失败");
        return ok;
    }

    //获取登录用户的发布的share
    @GetMapping("/getShareByUser")
    public ResultOk getShareByUser(@RequestHeader String userInfo) {
        ResultOk<List<Share>> ok = new ResultOk<>();
        User user = null;
        try {
            user = new ObjectMapper().readValue(userInfo, User.class);
            List<Share> shareList = shareService.getShareByUser(user.getUserId());
            if (shareList != null){
                ok.setCode(200);
                ok.setMsg("查询成功");
                ok.setData(shareList);
            } else {
                ok.setCode(400);
                ok.setMsg("暂无share，快去发布吧");
            }

        } catch (IOException e) {
            e.printStackTrace();
            ok.setCode(503);
            ok.setMsg("查询失败");
            return ok;
        }
        return ok;
    }

    //获取热门share
    @GetMapping("/getHotShare")
    public ResultOk getHotShare(@RequestHeader String userInfo) {
        ResultOk<List<Share>> ok = new ResultOk<>();
        User user = null;
        String key = "share:hotShare";
        List<Share> shareList = null;
        try {
            user = new ObjectMapper().readValue(userInfo, User.class);
            // 1.从redis查询hotShare
            String hotShareJson = stringRedisTemplate.opsForValue().get(key);
            // 2.判断是否存在
            if (StrUtil.isNotBlank(hotShareJson)) { //null、""、"/t" 都为false
                // 存在
                shareList = JSONUtil.toList(hotShareJson, Share.class);
                ok.setCode(200);
                ok.setMsg("查询成功");
                ok.setData(shareList);
                return ok;
            }
            // 3.判断命中的是否是空值
            if (hotShareJson != null) {
                // 返回错误信息
                ok.setCode(400);
                ok.setMsg("待会重试");
                return ok;
            }
            // 4.不存在，查数据库
            shareList = shareService.getHotShare(user.getUserId());
            if (shareList == null) {
                // 存入空值
                stringRedisTemplate.opsForValue().set(key,"",10, TimeUnit.MINUTES);
                ok.setCode(400);
                ok.setMsg("数据为空");
                return ok;
            }
            // 5.存在，写入redis
            stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shareList),10, TimeUnit.MINUTES);
            ok.setCode(200);
            ok.setMsg("查询成功");
            ok.setData(shareList);
        } catch (IOException e) {
            e.printStackTrace();
            ok.setCode(500);
            ok.setMsg("后端异常");
            return ok;
        }
        return ok;
    }

    //获取好友的share
    @GetMapping("/getFriendShare")
    public ResultOk getFriendShare(@RequestHeader String userInfo) {
        ResultOk<List<Share>> ok = new ResultOk<>();
        User user = null;
        try {
            user = new ObjectMapper().readValue(userInfo, User.class);
            List<Share> shareList = shareService.getFriendShare(user.getUserId());
            if (shareList != null){
                ok.setCode(200);
                ok.setMsg("查询成功");
                ok.setData(shareList);
            } else {
                ok.setCode(400);
                ok.setMsg("暂无share");
            }
        } catch (IOException e) {
            e.printStackTrace();
            ok.setCode(503);
            ok.setMsg("查询失败");
            return ok;
        }
        return ok;
    }

}
